package elitequant.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.util.Date;

import elitequant.order.FillEvent;
import elitequant.util.UtilFunc;

/**
 * A basic compliance module which writes trades to a CSV file in the output
 * directory.
 * 
 */
public class ExampleTradeRecorder extends TradeRecorderBase {

    private String outputDir;

    private String csvFilename;

    private BufferedWriter writer;

    /**
     * Wipe the existing trade log for the day, leaving only the headers in an
     * empty CSV.
     * 
     * It allows for multiple backtests to be run in a simple way, but quite
     * likely makes it unsuitable for a production environment that requires
     * strict record-keeping.
     * 
     * @param outputDir
     */
    public ExampleTradeRecorder(String outputDir) {
        this.outputDir = outputDir;

        // Remove the previous CSV file
        csvFilename = String.format("tradelog_%tF.csv", new Date());
        File csvFile = new File(outputDir, csvFilename);
        if (!csvFile.delete()) {
            System.out.println("No tradelog files to clean.");
        }
        //
        try {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFilename), "UTF-8"));

            // header
            writer.write(
                    "timestamp,ticker,action,quantity,exchange,price,commission");
        } catch (Exception e) {
            // ignore
        }
    }

    /**
     * Append all details about the FillEvent to the CSV trade log.
     * 
     */
    @Override
    public void recordTrade(FillEvent fill) {

        try {
            writer.newLine();
            String line = String.format("%s,%s,%s,%s,%s,%s,%s",
                    UtilFunc.formatDate(fill.timestamp), 
                    fill.fullSymbol,
                    fill.exchange,
                    String.valueOf(fill.brokerOrderId),
                    String.valueOf(fill.fillSize),
                    UtilFunc.formatMoney(fill.fillPrice),
                    UtilFunc.formatMoney(fill.commission));
        } catch (Exception e) {
            System.out.println("Record trade error");
        }

    }

    @Override
    protected void finalize() throws Throwable {
        writer.close();
    }

}
